package com.iot.aliyun.utils;



import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.iot.aliyun.handler.ResultHandler;
import com.iot.commonutils.utils.Result;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class JobUtil {

    //公共参数

    String regionId="cn-shanghai";//注册地ID

    String accessKeyId="LTAI4G2LfkTureHi7wPqy6Sv";

    String secret="7nv340IB0cPz776aphznfuNrpxAUXM";

    String iotInstanceId;//企业实例ID

    String sysDomain="iot."+regionId+".aliyuncs.com";//系统域名

    String sysVersion="2018-01-20";//系统版本

    /**
     * 调用该接口创建设备分发任务，默认同时分发设备所属产品
     * @param DeviceNames 待分发的设备名称列表
     * @param ProductKey 设备所属产品的唯一标识
     * @param SourceInstanceId 设备所属源实例id（不管是企业实例还是公共示例都需要传入）
     * @param Strategy 分发策略 0：指定的地域（只能分发到一个实例） 1：就近接入（可以分发到多个实例）
     * @param TargetInstanceConfigs 设备分发目标实例配置
     * @param TargetUid 设备所属的阿里云帐号id
     * @param TargetAliyunId 设备所属的阿里云帐号
     *                       TargetUid与TargetAliyunId参数至少传入一个
     * @return
     */
    public Result CreateDeviceDistributeJob(List<String> DeviceNames, String ProductKey, String SourceInstanceId, Integer Strategy,
                                            List<String> TargetInstanceConfigs, String TargetUid, String TargetAliyunId){
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(sysDomain);
        request.setSysVersion(sysVersion);
        request.setSysAction("CreateDeviceDistributeJob");
        request.putQueryParameter("RegionId", regionId);
        if (DeviceNames!=null){
            for (int i=0;i<DeviceNames.size();i++){
                request.putQueryParameter("DeviceName."+(i+1),DeviceNames.get(i));
            }
        }
        request.putQueryParameter("ProductKey",ProductKey);
        request.putQueryParameter("SourceInstanceId",SourceInstanceId);
        request.putQueryParameter("Strategy", Strategy.toString());
        if (TargetInstanceConfigs!=null){
            for (int i=0;i<TargetInstanceConfigs.size();i++){
                request.putQueryParameter("TargetInstanceConfig."+(i+1)+".TargetInstanceId",TargetInstanceConfigs.get(i));
            }
        }
        request.putQueryParameter("TargetUid",TargetUid);
        request.putQueryParameter("TargetAliyunId",TargetAliyunId);
        try {
            CommonResponse response = client.getCommonResponse(request);
            return ResultHandler.dataResultHandler(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.error("阿里云底层处理错误");
    }

    /**
     * 调用该接口创建产品分发任务
     * @param ProductKey 待分发产品的唯一标识
     * @param SourceInstanceId 产品所属的源实例id
     * @param TargetInstanceId 产品分发的目标实例id
     * @param TargetUid 产品所属的阿里云帐号id
     * @param TargetAliyunId 产品所属的阿里云帐号
     *                       TargetUid与TargetAliyunId参数至少传入一个。
     * @return
     */
    public Result CreateProductDistributeJob(String ProductKey,String SourceInstanceId,String TargetInstanceId,String TargetUid, String TargetAliyunId){
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(sysDomain);
        request.setSysVersion(sysVersion);
        request.setSysAction("CreateProductDistributeJob");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("ProductKey",ProductKey);
        request.putQueryParameter("SourceInstanceId",SourceInstanceId);
        request.putQueryParameter("TargetInstanceId", TargetInstanceId);
        request.putQueryParameter("TargetUid",TargetUid);
        request.putQueryParameter("TargetAliyunId",TargetAliyunId);
        try {
            CommonResponse response = client.getCommonResponse(request);
            return ResultHandler.dataResultHandler(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.error("阿里云底层处理错误");
    }

    /**
     * 调用该接口获取设备分发任务的详细信息
     * @param JobId 分发任务ID。任务的全局唯一标识符
     * @return
     */
    public Result QueryDeviceDistributeJob(String JobId){
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(sysDomain);
        request.setSysVersion(sysVersion);
        request.setSysAction("QueryDeviceDistributeJob");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("JobId",JobId);
        try {
            CommonResponse response = client.getCommonResponse(request);
            return ResultHandler.dataResultHandler(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.error("阿里云底层处理错误");
    }

    /**
     * 调用该接口获取设备分发任务执行完成后的结果信息
     * @param JobId 设备分发任务id（任务的全局唯一标识符），可通过CreateDeviceDistributeJob接口获取
     * @return String File:分发结果的文件URL，即文件在对象存储（OSS）上的存储地址，有效期为10分钟。
     */
    public Result QueryDeviceDistributeDetail(String JobId){
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(sysDomain);
        request.setSysVersion(sysVersion);
        request.setSysAction("QueryDeviceDistributeDetail");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("JobId",JobId);
        try {
            CommonResponse response = client.getCommonResponse(request);
            return ResultHandler.dataResultHandler(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.error("阿里云底层处理错误");
    }

    /**
     * 调用该接口获取设备分发任务列表
     * @param CurrentPage 指定从返回结果中的第几页开始显示。默认值是1
     * @param PageSize 每页显示的分发任务数量。最大不超过200条
     * @param TargetUid 阿里云账号ID
     * @param Status 分发任务状态
     *               0：任务初始化。
     *               1：任务执行中。
     *               2：任务完成。该状态仅表示分发任务执行完成，不表示所有产品和设备都分发成功。获取分发结果详情，请调用QueryDeviceDistributeDetail。
     *               3：任务异常中断。
     * @return
     */
    public Result ListDeviceDistributeJob(Integer CurrentPage,Integer PageSize,String TargetUid,Integer Status){
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(sysDomain);
        request.setSysVersion(sysVersion);
        request.setSysAction("ListDeviceDistributeJob");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("CurrentPage",CurrentPage.toString());
        request.putQueryParameter("PageSize",PageSize.toString());
        request.putQueryParameter("Status",Status.toString());
        request.putQueryParameter("TargetUid",TargetUid);
        try {
            CommonResponse response = client.getCommonResponse(request);
            return ResultHandler.dataResultHandler(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.error("阿里云底层处理错误");
    }

    /**
     * 调用该接口删除设备分发任务
     * @param JobId 分发任务id 任务的全局唯一标识符
     * @return
     */
    public Result DeleteDeviceDistributeJob(String JobId){
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(sysDomain);
        request.setSysVersion(sysVersion);
        request.setSysAction("DeleteDeviceDistributeJob");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("JobId",JobId);
        try {
            CommonResponse response = client.getCommonResponse(request);
            return ResultHandler.dataResultHandler(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.error("阿里云底层处理错误");
}

    //任务管理相关API
    /**
     * 调用该接口创建设备任务
     * @param JobDocument 下发给设备的任务执行规则文件，数据格式为Json
     * @param JobName 任务名称，支持中文、英文字母、数字和下划线，长度为4-30字符
     * @param TargetConfig 设备任务的目标设备配置
     * @param Type 任务类型。取值：INVOKE_SERVICE：设备批量服务调用任务。
     *                              SET_PROPERTY：设备批量属性设置任务。
     *                              CUSTOM_JOB：自定义任务
     * @param Description 任务的描述信息，长度不超过100个字符
     * @param JobFile 自定义任务中下发给设备的文件。仅Type为CUSTOM_JOB时，可传入此参数，且为非必传参数
     * @param TimeoutConfig 任务下作业执行的超时配置
     * @param RolloutConfig 任务下作业推送速率配置
     * @return
     */
    public Result CreateJob(String JobDocument, String JobName, JSONObject TargetConfig, String Type, String Description, JSONObject JobFile, JSONObject TimeoutConfig, JSONObject RolloutConfig){
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(sysDomain);
        request.setSysVersion(sysVersion);
        request.setSysAction("CreateJob");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("JobDocument",JobDocument);
        request.putQueryParameter("JobName",JobName);
        request.putQueryParameter("TargetConfig",TargetConfig.toString());
        request.putQueryParameter("Type",Type);
        request.putQueryParameter("IotInstanceId",iotInstanceId);
        request.putQueryParameter("Description",Description);
        if (JobFile!=null){
            request.putQueryParameter("JobFile",JobFile.toString());
        }
        if (TimeoutConfig!=null){
            request.putQueryParameter("TimeoutConfig",TimeoutConfig.toString());
        }
        if (RolloutConfig!=null){
            request.putQueryParameter("RolloutConfig",RolloutConfig.toString());
        }
        try {
            CommonResponse response = client.getCommonResponse(request);
            return ResultHandler.dataResultHandler(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.error("阿里云底层处理错误");
    }

    /**
     * 调用该接口删除任务
     * @param JobId 任务的唯一标识
     * @return
     */
    public Result DeleteJob(String JobId){
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(sysDomain);
        request.setSysVersion(sysVersion);
        request.setSysAction("DeleteJob");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("JobId",JobId);
        request.putQueryParameter("IotInstanceId",iotInstanceId);
        try {
            CommonResponse response = client.getCommonResponse(request);
            return ResultHandler.dataResultHandler(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.error("阿里云底层处理错误");
    }
}
